package com.yang.drawcard.web.oldbrowser;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.core.ui.loader.LatteLoader;
import com.core.utils.exit.ExitAppUtils;
import com.yang.drawcard.R;
import com.yang.drawcard.application.ConstValues;
import com.yang.drawcard.base.BaseActivity;
import com.yang.drawcard.utils.ViewUtil;
import com.yang.drawcard.web.JsBridge;
import com.yang.drawcard.web.JsInterface;

import java.lang.ref.SoftReference;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.app.ActivityCompat;


/**
 *
 */
public class WebPicActivity extends BaseActivity implements View.OnClickListener, JsBridge {

    public static final String TAG = WebPicActivity.class.getSimpleName();

    private RelativeLayout backBtn;
    private RelativeLayout confirmBtn;
    private AppCompatTextView confirmTv;
    private AppCompatTextView backTv;
    private AppCompatTextView titleTv;

    private WebView web;
    private RelativeLayout rl_next;

    MyHandler handler;

    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<WebPicActivity> fragmentRef;

        public MyHandler(WebPicActivity fragment) {
            fragmentRef = new SoftReference<WebPicActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            WebPicActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }
            Bundle bundle = msg.getData();

            // 处理UI 变化
            switch (msg.what) {
                case ConstValues.WAIT0:
                    fragment.finishSuc();
                    break;
                case ConstValues.WAIT1:
                    // fragment.showShareWx(bundle);
                    break;
                case ConstValues.WAIT2:
                    // fragment.showTzAdapter();
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_pic);


        backBtn = (RelativeLayout) findViewById(R.id.top_dd_navigation_rl_back);
        confirmBtn = (RelativeLayout) findViewById(R.id.top_dd_navigation_rl_confirm);
        confirmTv = (AppCompatTextView) findViewById(R.id.top_dd_navigation_bt_confirm);
        backTv = (AppCompatTextView) findViewById(R.id.top_dd_navigation_bt_back);
        titleTv = (AppCompatTextView) findViewById(R.id.top_dd_navigation_tv_title);
        confirmBtn.setVisibility(View.INVISIBLE);
        //confirmBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);


        web = (WebView) findViewById(R.id.pic_yd_web);

        backBtn.setOnClickListener(this);

        // 沉浸式
        setStatusBar();

        handler = new MyHandler(this);

        Intent i = getIntent();
        String url = i.getStringExtra("url");
        String title = i.getStringExtra("title");

        titleTv.setText(title);

        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setSupportZoom(true);
        web.getSettings().setBuiltInZoomControls(true);
        web.getSettings().setUseWideViewPort(true);//关键点
        web.getSettings().setLoadWithOverviewMode(true);
        web.getSettings().setDisplayZoomControls(false);//隐藏缩放工具
        web.getSettings().setBlockNetworkImage(false);//解决图片不显示

        //其他细节操作
        web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); //不使用缓存，只从网络获取数据.
        web.getSettings().setAllowFileAccess(true); //设置可以访问文件
        web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        web.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片
        web.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式


        // 通过addJavascriptInterface()将Java对象映射到JS对象
        //参数1：Javascript对象名
        //参数2：Java对象名
        web.addJavascriptInterface(new JsInterface(this), "latte");//AndroidtoJS类对象映射到js的test对象

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // WebView.setWebContentsDebuggingEnabled(true);
            web.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        web.setWebViewClient(new WebViewClient() {
            /*@Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // view.loadUrl(url);
                web.loadUrl(url);
                return true;
            }*/

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                //设定加载开始的操作
                // LatteLoader.showLoading(YdWebActivity.this);

                if(ExitAppUtils.getInstance().getAllActivity().contains(WebPicActivity.this)){
                    LatteLoader.showLoading(WebPicActivity.this);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                //设定加载结束的操作
                LatteLoader.stopLoading();
            }


            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();    //表示等待证书响应
                // handler.cancel();      //表示挂起连接，为默认方式
                // handler.handleMessage(null);    //可做其他处理
            }
        });


        web.setOnLongClickListener(new View.OnLongClickListener() {

            public boolean onLongClick(View v) {
                WebView.HitTestResult result = web.getHitTestResult();
                if (null == result)
                    return false;
                int type = result.getType();
                switch (type) {
                    case WebView.HitTestResult.EDIT_TEXT_TYPE: // 选中的文字类型
                        break;
                    case WebView.HitTestResult.PHONE_TYPE: // 处理拨号
                        break;
                    case WebView.HitTestResult.EMAIL_TYPE: // 处理Email
                        break;
                    case WebView.HitTestResult.GEO_TYPE: // 　地图类型
                        break;
                    case WebView.HitTestResult.SRC_ANCHOR_TYPE: // 超链接
                        break;
                    case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: // 带有链接的图片类型
                    case WebView.HitTestResult.IMAGE_TYPE: // 处理长按图片的菜单项
                        String url = result.getExtra();
                        downPicDate(url);
                        return true;
                    case WebView.HitTestResult.UNKNOWN_TYPE: //未知
                        break;
                }
                return false;
            }
        });

        web.loadUrl(url);
        // web.loadUrl("file:///android_asset/Javascriptt.html");

    }

    @Override
    public void setTextValue(String value) {

        /*handler.post(new Runnable() {
            @Override
            public void run() {
                YdWebActivity.this.finish();
            }
        });*/

        handler.sendEmptyMessage(ConstValues.WAIT0);

    }

    @Override
    public void setCallShare(String value) {

        /*handler.post(new Runnable() {
            @Override
            public void run() {
                YdWebActivity.this.finish();
            }
        });*/

        Bundle bundle = new Bundle();
        bundle.putString("formjson", value);
        Message msg = new Message();
        msg.what = ConstValues.WAIT1;
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    private void finishSuc() {
        WebPicActivity.this.finish();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) { //
            case R.id.top_dd_navigation_rl_back://
                if (ViewUtil.isDoubleClick(v.getId(), 2500))
                    return;
                this.finish();

                break;
        }
    }

    // 对返回键进行监听
    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            ActivityCompat.finishAfterTransition(this);
        }
    }

    @Override
    protected void onDestroy() {
        if (web != null) {
            web.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            web.clearHistory();

            ((ViewGroup) web.getParent()).removeView(web);
            web.destroy();
            web = null;
        }
        super.onDestroy();
    }

}
